<template>
  <div class="order-history">
    <h2>我的购买历史</h2>
    
    <div v-if="loading" class="loading">加载中...</div>
    
    <div v-else-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>
    
    <div v-else-if="orderList.length === 0" class="empty">
      暂无订单记录
    </div>
    
    <ul v-else class="order-list">
      <li v-for="order in orderList" :key="order.id" class="order-item">
        <div class="order-info">
          <div class="order-header">
            <span class="order-number">订单号: {{ order.order_fake?.order_number || '未知' }}</span>
            <span class="order-status" :class="getStatusClass(order.order_fake?.status || '')">
              {{ order.order_fake?.status || '未知状态' }}
            </span>
          </div>
          <div class="order-content">
            <div class="product-preview">
              <img 
                v-if="order.product?.image_url"
                :src="order.product.image_url" 
                :alt="order.product.name || '商品图片'" 
                class="product-img"
              >
              <span v-if="order.product?.name" class="product-name">
                {{ order.product.name }}
              </span>
            </div>
            <div class="order-summary">
              <p class="total-amount">总金额: ￥{{ formatPrice(order.order_fake?.total_amount) }}</p>
              <p class="create-time">{{ formatTime(order.created_time) }}</p>
              <button 
                v-if="order.order_fake?.status === '待支付'" 
                @click="handlePay(order.order_fake.id)" 
                class="pay-btn"
              >
                立即支付
              </button>
            </div>
          </div>
        </div>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { getOrderHistory } from '@/api/history';
import { useRoute } from 'vue-router';

// 状态管理
const loading = ref(true);
const errorMessage = ref('');
const orderList = ref([]);
const route = useRoute();

// 格式化价格
const formatPrice = (price) => {
  try {
    if (price === undefined || price === null) return '0.00';
    const numericPrice = Number(price);
    return isNaN(numericPrice) ? '0.00' : numericPrice.toFixed(2);
  } catch (error) {
    console.error('价格格式化错误:', error);
    return '0.00';
  }
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '未知时间';
  try {
    const date = new Date(time);
    if (isNaN(date.getTime())) return time;
    return date.toLocaleString();
  } catch (error) {
    console.error('时间格式化错误:', error);
    return time;
  }
};

// 获取订单状态的样式类
const getStatusClass = (status) => {
  const statusMap = {
    '待支付': 'status-pending',
    '已支付': 'status-paid',
    '已发货': 'status-shipped',
    '已完成': 'status-completed',
    '已取消': 'status-canceled'
  };
  return statusMap[status] || '';
};

const handlePay = (orderId) => {
  if (!orderId) {
    console.error('订单ID不存在');
    return;
  }
  console.log('前往支付，订单ID：', orderId);
};

onMounted(async () => {
  try {
    loading.value = true;
    errorMessage.value = '';

    const userId = route.params.userId || 1;
    if (!userId) {
      throw new Error('用户ID不存在');
    }

    const response = await getOrderHistory(userId);

    if (Array.isArray(response.data)) {
      orderList.value = response.data;
    } else {
      throw new Error('订单数据格式错误');
    }
  } catch (error) {
    console.error('获取订单历史失败:', error);
    errorMessage.value = error.response?.data?.message || error.message || '获取订单历史失败，请稍后再试';
  } finally {
    loading.value = false;
  }
});
</script>


<style scoped>
.order-history {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.loading, .empty, .error-message {
  text-align: center;
  padding: 30px;
  color: #666;
  font-size: 1.1em;
}

.error-message {
  color: #f5222d;
  background-color: #fff2f0;
  border-radius: 4px;
}

.order-list {
  list-style: none;
  padding: 0;
}

.order-item {
  margin-bottom: 15px;
  border: 1px solid #eee;
  border-radius: 6px;
  overflow: hidden;
  transition: box-shadow 0.2s;
}

.order-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #fafafa;
  border-bottom: 1px solid #eee;
}

.order-number {
  color: #666;
  font-size: 0.9em;
}

.order-status {
  font-weight: 500;
}

.status-pending { color: #fa8c16; } /* 橙色 */
.status-paid { color: #1890ff; } /* 蓝色 */
.status-shipped { color: #722ed1; } /* 紫色 */
.status-completed { color: #52c41a; } /* 绿色 */
.status-canceled { color: #bfbfbf; } /* 灰色 */

.order-content {
  display: flex;
  padding: 15px;
  gap: 15px;
}

.product-preview {
  position: relative;
}

.product-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.product-name {
  color: #666;
  font-size: 0.9em;
}

.order-summary {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.total-amount {
  font-weight: 600;
  color: #f5222d;
}

.create-time {
  color: #999;
  font-size: 0.9em;
}

.pay-btn {
  align-self: flex-end;
  background-color: #f5222d;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9em;
  transition: background-color 0.2s;
}

.pay-btn:hover {
  background-color: #d91111;
}
</style>